
//% color="#5a5dd0" iconWidth=50 iconHeight=40
namespace knn{

    //% block="读取数据" blockType="tag"
    export function readDataTag() {}

    //% block="读取数据集 路径[DIR] 结果存入变量[VAR]" blockType="command"
    //% DIR.shadow="string" DIR.defl="dataset.csv"
    //% VAR.shadow="normal" VAR.defl="pddata"
    export function readCsv(parameter: any, block: any) {
        let DIR=parameter.DIR.code; 
        let VAR=parameter.VAR.code; 
        Generator.addImport(`import warnings`)
        Generator.addCode(`warnings.filterwarnings("ignore")\n`)

        Generator.addImport(`import pandas as pd`)
        Generator.addCode(`${VAR} = pd.read_csv(${DIR})`)
        


    }
    //% block="获取数据集[OBJECT]标题行[STR]中整列的[VALVE]属性的数据" blockType="reporter"
    //% OBJECT.shadow="normal" OBJECT.defl="pddata"
    //% STR.shadow="normal" STR.defl="'Feature_1','Feature_2'"
    //% VALVE.shadow="dropdown" VALVE.options="VALVE"
    export function Pandas_initlowvalues(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;
        let str=parameter.STR.code;
        let valve=parameter.VALVE.code;
        if(`${valve}` === '1'){
            Generator.addCode(`${obj}[${str}]`) 
        }else{
            Generator.addCode(`${obj}[[${str}]].values `) 
        }
    }

    //% block="获取数据集[VAR]的前[INDEX]行数据" blockType="reporter"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% INDEX.shadow="normal" INDEX.defl="10"
    export function getDataHead(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        let INDEX=parameter.INDEX.code; 
        Generator.addCode(`${VAR}.head(${INDEX})`)

    }

    //% block="获取数据集[VAR]的维度信息" blockType="reporter"
    //% VAR.shadow="normal" VAR.defl="pddata"
    export function getDataShape(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        Generator.addCode(`${VAR}.shape`)

    }

    //% block="获取数据集[VAR]每一列空值数量" blockType="reporter"
    //% VAR.shadow="normal" VAR.defl="pddata"
    export function getDataIsnull(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        Generator.addCode(`${VAR}.isnull().sum()`)

    }

     //% block="获取数据集[VAR]存在重复值的数据行总数" blockType="reporter"
    //% VAR.shadow="normal" VAR.defl="pddata"
    export function getDataDuplicated(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        Generator.addCode(`${VAR}.duplicated().sum()`)

    }

    
    //% block="数据分析" blockType="tag"
    export function pltTag() {}

    
    //% block="设置图表窗口 宽[WIDE]高[HIGH]DPI[DPI]  工具栏[TOOLBAR]" blockType="command"
    //% WIDE.shadow="number" WIDE.defl="8"
    //% HIGH.shadow="number" HIGH.defl="6"
    //% DPI.shadow="number" DPI.defl="80"
    //% TOOLBAR.shadow="dropdown" TOOLBAR.options="TOOLBAR"
    export function pltSetting(parameter: any, block: any) {

        let TOOLBAR=parameter.TOOLBAR.code; 
        let WIDE=parameter.WIDE.code;
        let HIGH=parameter.HIGH.code;
        let DPI=parameter.DPI.code;

    Generator.addCode(`plt.rcParams['toolbar'] = '${TOOLBAR}'`)
    Generator.addCode(`plt.figure(figsize=(${WIDE}, ${HIGH}),dpi=${DPI})`)

    }

    //% block="绘制柱状图 用读取的数据集[VAR]的[X]列 标题为[TITLE] 字号[FSIZE]" blockType="command"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% TITLE.shadow="string" TITLE.defl="Title"
    //% X.shadow="string" X.defl="stress"
    //% FSIZE.shadow="number" FSIZE.defl="18"
    export function drawCountplot(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        let TITLE=parameter.TITLE.code; 
        let X=parameter.X.code; 
        let FSIZE=parameter.FSIZE.code; 

        Generator.addImport(`import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns`)
        Generator.addImport(`import platform\nimport sys`)
        Generator.addDeclaration("drawCountplot",`if "linux" in sys.platform:
    plt.rcParams['font.family'] = ['HYQiHei']
else:
    plt.rcParams['font.family'] = ['SimHei']`)
        Generator.addCode(`
plt.rcParams['axes.unicode_minus'] = False 
plt.figure(figsize=(10, 6))
plt.title(${TITLE},fontsize=${FSIZE}) 
sns.countplot(x=${X},data=${VAR},hue=${X},palette='deep')
plt.legend(title=${X},loc='upper right',bbox_to_anchor=(1.126, 1),fontsize=10)
`)
}
   //% block="绘制柱状图 图例显示[TITLE]" blockType="command"
    //% TITLE.shadow="normal" TITLE.defl="Title"
 
    export function drawCountplotA(parameter: any, block: any) {

        let TITLE=parameter.TITLE.code; 
        Generator.addCode(`
plt.legend(title=${TITLE}, bbox_to_anchor=(1.126, 1), loc='upper right', borderaxespad=0.)
`)
    }
    //% block="绘散点图 用读取的数据集[VAR]的[X]列标题为[TITLE] 字号[FSIZE]，散点大小[NUM]" blockType="command"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% TITLE.shadow="string" TITLE.defl="Title"
    //% X.shadow="list" X.defl="'Feature_1','Feature_2'"
    //% FSIZE.shadow="number" FSIZE.defl="18"
    //% NUM.shadow="number" NUM.defl="50"

    export function drawCountplot1(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        let TITLE=parameter.TITLE.code; 
        let X=parameter.X.code; 
        let FSIZE=parameter.FSIZE.code; 
        let NUM=parameter.NUM.code;


        Generator.addImport(`import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns`)
        Generator.addImport(`import platform\nimport sys`)
        Generator.addDeclaration("drawCountplot",`if "linux" in sys.platform:
    plt.rcParams['font.family'] = ['HYQiHei']
else:
    plt.rcParams['font.family'] = ['SimHei']`)
        Generator.addCode(`
plt.rcParams['axes.unicode_minus'] = False 
plt.title(${TITLE},fontsize=${FSIZE}) 
df_lie= ${X}
plt.scatter(${VAR}[df_lie[0]], ${VAR}[df_lie[1]], s=${NUM})
`)
    }

    //% block="绘制折线图 X轴[VAR] Y轴[X] 标题为[TITLE] 字号[FSIZE]，线宽[LWIDTH]" blockType="command"
    //% VAR.shadow="normal" VAR.defl="[1,2,3]"
    //% TITLE.shadow="string" TITLE.defl="Title"
    //% X.shadow="normal" X.defl="[20,10,10]"
    //% FSIZE.shadow="number" FSIZE.defl="18"
    //% LWIDTH.shadow="number" LWIDTH.defl="1"
    export function drawCountplot2(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        let TITLE=parameter.TITLE.code; 
        let X=parameter.X.code; 
        let FSIZE=parameter.FSIZE.code; 
        let LWIDTH=parameter.LWIDTH.code;

        Generator.addImport(`import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns`)
        Generator.addImport(`import platform\nimport sys`)
        Generator.addDeclaration("drawCountplot",`if "linux" in sys.platform:
    plt.rcParams['font.family'] = ['HYQiHei']
else:
    plt.rcParams['font.family'] = ['SimHei']`)
        Generator.addCode(`

plt.rcParams['axes.unicode_minus'] = False
plt.title(${TITLE},fontsize=${FSIZE})

plt.plot(${VAR}, ${X}, linewidth=${LWIDTH},marker='o')
`)
    }
    //% block="绘制热图 用读取的数据集[VAR] 标题为[TITLE] 字号[FSIZE] 小数位数[FMTB] 线宽[LWIDTH] " blockType="command"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% TITLE.shadow="string" TITLE.defl="Title"
    //% LWIDTH.shadow="normal" LWIDTH.defl="0.1"
    //% FMTB.shadow="number" FMTB.defl="3"
    //% FSIZE.shadow="number" FSIZE.defl="18"
    export function drawheatmap(parameter: any, block: any) {
        let VAR=parameter.VAR.code; 
        let TITLE=parameter.TITLE.code; 
        let LWIDTH=parameter.LWIDTH.code; 
        let FMTB=parameter.FMTB.code; 
        let FSIZE=parameter.FSIZE.code; 

        Generator.addImport(`import matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns`)
        Generator.addImport(`import platform\nimport sys`)
        Generator.addDeclaration("drawCountplot",`if "linux" in sys.platform:
    plt.rcParams['font.family'] = ['HYQiHei']
else:
    plt.rcParams['font.family'] = ['SimHei']`)

        Generator.addCode(`
plt.rcParams['axes.unicode_minus'] = False 
plt.figure(figsize=(12, 10),dpi=80)
sns.heatmap(${VAR}[${VAR}.columns].corr(),annot=True,
            cmap = sns.diverging_palette(220, 10, as_cmap = True),
            linewidths=${LWIDTH}, fmt='.${FMTB}f' ) 
plt.title(${TITLE},fontsize=${FSIZE})
`)
    }

    //% block="修改图表 [LABEL] 标题[TXET]字号[SIZE] 参数字号[SIZE2]" blockType="command"
    //% LABEL.shadow="dropdown" LABEL.options="LABEL"
    //% TXET.shadow="string" TXET.defl="Title"
    //% SIZE.shadow="number" SIZE.defl="16"
    //% SIZE2.shadow="number" SIZE2.defl="10"
    export function matplotlib_label(parameter: any, block: any) {
        let LABEL=parameter.LABEL.code;
        let TXET=parameter.TXET.code;
        let SIZE=parameter.SIZE.code;
        let SIZE2=parameter.SIZE2.code;
        console.log(LABEL)
        if(LABEL=="x")
        {
            Generator.addCode(`plt.xticks(fontsize=${SIZE2})  `)
            Generator.addCode(`plt.xlabel(${TXET},fontsize=${SIZE}) `)
        }
        if(LABEL=="y")
        {
            Generator.addCode(`plt.yticks(fontsize=${SIZE2})  `)
            Generator.addCode(`plt.ylabel(${TXET},fontsize=${SIZE})  `)
        }
        
    }   
    //% block="将图表保存[IMG]" blockType="command"
    //% IMG.shadow="string" IMG.defl="img.png"
    export function pltSave(parameter: any, block: any) {
        let IMG=parameter.IMG.code;

        Generator.addCode(`plt.savefig(${IMG})`)

    }
    //% block="将图表显示出来" blockType="command"
    export function pltShow(parameter: any, block: any) {

        Generator.addCode(`plt.show()`)

    }

    //% block="数据处理" blockType="tag"
    export function dataDropTag() {}

    //% block="将数据集[VAR]移除列名[FIELD]后的数据作为特征数据存入变量[VAR2]" blockType="command"
    //% FIELD.shadow="string" FIELD.defl="stress"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% VAR2.shadow="normal" VAR2.defl="feature"
    export function dataDrop(parameter: any, block: any) {
        let FIELD=parameter.FIELD.code; 
        let VAR=parameter.VAR.code; 
        let VAR2=parameter.VAR2.code; 

        Generator.addCode(`${VAR2} = ${VAR}.drop(${FIELD},axis=1)`)

    }

    //% block="将数据集[VAR]列名[FIELD]的数据作为标签数据存入变量[VAR3]" blockType="command"
    //% FIELD.shadow="string" FIELD.defl="stress"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% VAR3.shadow="normal" VAR3.defl="target"
    export function dataTaget(parameter: any, block: any) {
        let FIELD=parameter.FIELD.code; 
        let VAR=parameter.VAR.code; 
        let VAR3=parameter.VAR3.code; 
  
        Generator.addCode(`${VAR3} = ${VAR}[${FIELD}]`)

    }

    //% block="将数据集[VAR]列名[FIELD]的数据作为特征数据存入变量[VAR3]" blockType="command"
    //% FIELD.shadow="list" FIELD.defl="'snore','breath','temperature'"
    //% VAR.shadow="normal" VAR.defl="pddata"
    //% VAR3.shadow="normal" VAR3.defl="feature2"
    export function dataTaget2(parameter: any, block: any) {
        let FIELD=parameter.FIELD.code; 
        let VAR=parameter.VAR.code; 
        let VAR3=parameter.VAR3.code; 

        Generator.addCode(`${VAR3} = ${VAR}[${FIELD}]`)
    }

    //% block="将特征[VAR2]和标签[VAR3]进行数据集划分 测试集占比[SIZE] 结果存入变量[VAR5]" blockType="command"
    //% VAR2.shadow="normal" VAR2.defl="feature"
    //% VAR3.shadow="normal" VAR3.defl="target"
    //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    //% SIZE.shadow="number" SIZE.defl=0.5
    export function trainTestSplit(parameter: any, block: any) {
        let VAR2=parameter.VAR2.code; 
        let VAR3=parameter.VAR3.code; 
        let VAR5=parameter.VAR5.code; 
        let SIZE=parameter.SIZE.code; 
        Generator.addImport(`from sklearn.model_selection import train_test_split`)
        Generator.addCode(`${VAR5}= train_test_split(${VAR2}, ${VAR3},test_size=${SIZE},random_state=10,stratify=${VAR3})`)

    }

    //% block="从划分后数据集[VAR5]中取[SDATA]" blockType="reporter"
    //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    //% SDATA.shadow="dropdown" SDATA.options="SDATA"
    export function SDataGet(parameter: any, block: any) {
        let VAR5=parameter.VAR5.code; 
        let SDATA=parameter.SDATA.code; 

        Generator.addCode(`${VAR5}[${SDATA}]`)

    }

    //% block="模型训练" blockType="tag"
    export function knnTag() {}


    //% block="创建KNN分类器[KNN] K值为[KVAL]" blockType="command"
    //% KVAL.shadow="number" KVAL.defl="3"
    //% KNN.shadow="normal" KNN.defl="knn"
    export function initKNNn(parameter: any, block: any) {
        let KVAL=parameter.KVAL.code; 
        let KNN=parameter.KNN.code; 
        Generator.addImport(`from sklearn.neighbors import KNeighborsClassifier`)
        Generator.addCode(`${KNN} = KNeighborsClassifier(n_neighbors=${KVAL})`)

    }

    //% block="KNN分类器[KNN] 使用划分后数据集[VAR5]中的训练集数据 进行模型训练" blockType="command"
    //% KNN.shadow="normal" KNN.defl="knn"
    //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    export function KNNFit(parameter: any, block: any) {
        let VAR5=parameter.VAR5.code; 
        let KNN=parameter.KNN.code; 

        Generator.addCode(`${KNN} = ${KNN}.fit(${VAR5}[0], ${VAR5}[2])`)

    }
    
    //% block="KNN分类器[KNN] 导出模型[PATH]" blockType="command"
    //% KNN.shadow="normal" KNN.defl="knn"
    //% PATH.shadow="string" PATH.defl="model.pkl"
    export function KNNdumpmodel(parameter: any, block: any) {
        let knn=parameter.KNN.code; 
        let path=parameter.PATH.code; 

        Generator.addImport(`import joblib`)
        Generator.addCode(`joblib.dump(${knn}, ${path})`)

    }
    
    //% block="加载KNN模型[PATH]" blockType="reporter"
    //% PATH.shadow="string" PATH.defl="model.pkl"
    export function KNNloadmodel(parameter: any, block: any) {
        let path=parameter.PATH.code; 

        Generator.addImport(`import joblib`)
        Generator.addCode(`joblib.dump(${path})`)

    }
    //% block="KNN分类器[KNN] 使用划分后数据集[VAR5]中的测试集 计算准确率" blockType="reporter"
    //% KNN.shadow="normal" KNN.defl="knn"
    //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    export function KNNScore(parameter: any, block: any) {
        let VAR5=parameter.VAR5.code; 
        let KNN=parameter.KNN.code; 

        Generator.addCode(`${KNN}.score(${VAR5}[1], ${VAR5}[3])`)

    }


    //% block="KNN分类器[KNN] 使用输入值[VAR8] 进行预测" blockType="reporter"
    //% KNN.shadow="normal" KNN.defl="knn"
    //% VAR8.shadow="normal" VAR8.defl="test_values"
    export function KNNpredict(parameter: any, block: any) {
        let VAR8=parameter.VAR8.code; 
        let KNN=parameter.KNN.code; 

        Generator.addCode(`${KNN}.predict(${VAR8})`)

    }

    //% block="KNN分类器[KNN] 使用输入值[VAR8] 进行预测" blockType="reporter"
    //% KNN.shadow="normal" KNN.defl="knn"
    //% VAR8.shadow="list" VAR8.defl="25,45,2000,0"
    export function KNNpredict2(parameter: any, block: any) {
        let VAR8=parameter.VAR8.code; 
        let KNN=parameter.KNN.code; 
        Generator.addImport(`import numpy as np`)
        Generator.addCode(`${KNN}.predict(np.array(${VAR8}).reshape(1, -1))`)

    }

    //% block="从划分后数据集[VAR5]中取[SDATA]的真实标签" blockType="reporter"
    //% VAR5.shadow="normal" VAR5.defl="dataSplit"
    //% SDATA.shadow="dropdown" SDATA.options="SDATA"
    export function SDataGetValues(parameter: any, block: any) {
        let VAR5=parameter.VAR5.code; 
        let SDATA=parameter.SDATA.code; 

        Generator.addCode(`${VAR5}[${SDATA}].values`)

    }
    //% block="---" blockType="tag"
    export function KMeansTag() {}

    //% block="创建KMeans聚类[KMeans]，K值为[KVAL]，迭代次数[NUM]，[SHOW]显示每次迭代" blockType="command"
    //% KVAL.shadow="number" KVAL.defl="3"
    //% KMeans.shadow="normal" KMeans.defl="KMeans"
    //% NUM.shadow="number" NUM.defl="150"
    //% SHOW.shadow="dropdown" SHOW.options="SHOW"
    export function initKMeans(parameter: any, block: any) {
        let KVAL=parameter.KVAL.code; 
        let KMeans=parameter.KMeans.code; 
        let NUM=parameter.NUM.code;
        let SHOW=parameter.SHOW.code;
        Generator.addImport(`from kmeans_cluster import KMeansCluster`)
        Generator.addCode(`${KMeans} = KMeansCluster(k=${KVAL}, max_iters=${NUM}, plot_steps=${SHOW})`)

    }
    //% block="KMeans聚类[KMeans] 使用输入值[VAR8] 进行预测并选择[SYOW]每次迭代数据" blockType="command"
    //% KMeans.shadow="normal" KMeans.defl="KMeans"
    //% VAR8.shadow="list" VAR8.defl="25,45,2000,0"
    //% SYOW.shadow="dropdown" SYOW.options="SYOW"
    export function KMeanspredict2(parameter: any, block: any) {
        let KMeans=parameter.KMeans.code;
        let VAR8=parameter.VAR8.code; 
        let SYOW=parameter.SYOW.code;
        Generator.addCode(`KMeans_labels, KMeans_metrics, KMeans_count= ${KMeans}.predict(${VAR8}, ${SYOW})`)

    }
    //% block="获取计算迭[SSCD]数据" blockType="reporter"
    //% SSCD.shadow="dropdown" SSCD.options="SSCD"
    export function KMeanspredict3(parameter: any, block: any) {
        let SSCD=parameter.SSCD.code;
        Generator.addCode(`(KMeans_metrics['${SSCD}'])`)

    }
    //% block="KMeans聚类[KMeans]绘制[SHOW]数据 标题为[TITLE]的最优图表" blockType="command"
    //% KMeans.shadow="normal" KMeans.defl="KMeans"
    //% SHOW.shadow="normal" SHOW.defl="25,45,2000,0"
    //% TITLE.shadow="string" TITLE.defl="Final Clustering Result"
    
    export function KMeanspredict31(parameter: any, block: any) {
        let KMeans=parameter.KMeans.code;
        let SHOW=parameter.SHOW.code;
        let TITLE=parameter.TITLE.code;
        
        Generator.addCode(`${KMeans}.plot_metrics(${SHOW},${KMeans},${TITLE})`)

    }
    //% block="---" blockType="tag"
    export function KMeansTag1() {}

    //% block="输入数据集特征数据[DATA]通过肘部方法计算不同变量[K_va] K值 1~[K] 下的误差平方和[SSE]" blockType="command"
    //% DATA.shadow="normal" DATA.defl="feature"
    //% K_va.shadow="normal" K_va.defl="k_values"
    //% K.shadow="number" K.defl="6"
    //% SSE.shadow="normal" SSE.defl="sse"
    export function KMeanspredict4(parameter: any, block: any) {
        let DATA=parameter.DATA.code;
        let K_va=parameter.K_va.code;
        let K=parameter.K.code;
        let SSE=parameter.SSE.code;
        Generator.addImport(`from sklearn.cluster import KMeans`)
        Generator.addCode(`${SSE} = []
${K_va} = range(1, ${K}+1)
for k in ${K_va}:
    kmeans_va = KMeans(n_clusters=k, init='k-means++', random_state=42)
    kmeans_va.fit(${DATA})
    ${SSE}.append(kmeans_va.inertia_)`)
    }
    //% block="通过KMeans聚类，K值为[K] 标题为[TITLE]对[VAR8]数据进行预测并绘制图表显示" blockType="command"
    //% K.shadow="number" K.defl="6"
    //% VAR8.shadow="list" VAR8.defl="25,45,2000,0"
    //% TITLE.shadow="string" TITLE.defl="title"
    export function KMeanspredict5(parameter: any, block: any) {
        let K=parameter.K.code;
        let VAR8=parameter.VAR8.code;
        let TITLE=parameter.TITLE.code;
        Generator.addImport(`from sklearn.cluster import KMeans`)
        Generator.addCode(`kmeans_cl = KMeans(n_clusters=${K}, init='k-means++', random_state=42)
y_pred = kmeans_cl.fit_predict(${VAR8})
plt.scatter(${VAR8}[:, 0], ${VAR8}[:, 1], c=y_pred, s=50, cmap='viridis')
centroids = kmeans_cl.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, marker='X', label='质心')
plt.title(${TITLE},fontsize=18)
plt.legend()

`)
        }

}


